#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/7/20 11:54
# @File : KuaiPuContract.py
# @Email : fortunatedong@163.com

import time

import pandas as pd
from selenium.common import NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
import selenium.webdriver.support.wait as WA
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from PIL import Image
from aip import AipOcr
import os
from logger import Loggings
loggins = Loggings()

class Contract_upload():
    def __init__(self):
        # webdriver的路径
        gecko_driver_path = 'C:/Users/admin/AppData/Local/Google/Chrome/Application/chromedriver.exe'

        service = Service(executable_path=gecko_driver_path)
        self.driver = webdriver.Chrome(service=service)
        # 打开网页

    def get_file_content(self,file_path):
        with open(file_path, 'rb') as f:
            return f.read()
    def get_pic(self):
        png = self.driver.find_element(By.XPATH,"//img[@id='ctrlValidateCode_imgCode']")  # 查找验证码元素
        png.screenshot('capt.png')  # 对验证码进行截图并保存
        img = Image.open('capt.png')
        img = img.convert('L')  # P模式转换为L模式(灰度模式默认阈值127)
        count = 165  # 设定阈值
        filter_func = lambda x: 0 if x < count else 1
        img = img.point(filter_func, '1')
        img.save('captcha1.png')
        APP_ID = '96350634'
        API_KEY = '4JsJuf7rfgyANXA14QjnJeSJ'
        SECRET_KEY = 'fJLtJnGjwMjzFVdLK4l14jFTx6p9jZcw'
        # 初始化对象
        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
        image = self.get_file_content('captcha1.png')
        # 定义参数变量
        options = {'language_type': 'ENG', }  # 识别语言类型，默认为'CHN_ENG'中英文混合
        # 调用通用文字识别
        result = client.basicGeneral(image, options)# 高精度接口 basicAccurate
        loggins.info(f"文字识别结果：{result}")
        if 'words_result' in result:
            text = (''.join([w['words'] for w in result['words_result']])).replace(" ","")
            return text
    def login(self):
        """http://172.16.0.20:2024/"""
        # url = "http://172.16.0.20:8888/"
        url = "http://172.16.0.20:2024/"
        self.driver.get(url)
        # 等待页面加载完成
        wait = WebDriverWait(self.driver, 10)
        self.driver.find_element(By.XPATH, "//input[@id='txtLoginName']").send_keys("xxxxxxxxx")
        time.sleep(1)
        self.driver.find_element(By.XPATH, "//input[@id='txtPwd']").send_keys("xxxxxxxxxxxx")
        # time.sleep(1)
        time.sleep(3)
        # a = input("")
        captcha = self.get_pic()
        loggins.info(f"登录验证码：{captcha}")
        self.driver.find_element(By.XPATH, "//input[@id='txtValidate']").send_keys(captcha)
        self.driver.find_element(By.XPATH, "//input[@id='btnLogin']").click()
        time.sleep(2)
        return self.driver

    def search(self):
        self.driver = self.login()
        time.sleep(2)
        handles = self.driver.window_handles  # 获取当前浏览器的所有窗口句柄
        loggins.info(f"所有窗口句柄：{handles}")
        self.driver.switch_to.window(handles[-1])  # 切换到最新打开的窗口
        # self.driver.switch_to.window(handles[-2])  # 切换到倒数第二个打开的窗口
        # self.driver.switch_to.window(handles[0])  # 切换到最开始打开的窗口

        try:
            element = self.driver.find_element(By.XPATH, "//input[@id='txtSearch']")
            loggins.info("搜索按键元素存在")
            element.click()
        except NoSuchElementException:
            loggins.error("搜索按键元素不存在")
        try:
            element = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, "//input[@id='txtSearch']"))
            )
            loggins.info("搜索按键元素可点击")
        except TimeoutException:
            loggins.error("搜索按键元素不可点击")
        # WA.WebDriverWait(self.driver, timeout=2).until(EC.frame_to_be_available_and_switch_to_it("iframe_0_0_main"))
        self.driver.find_element(By.XPATH, "//input[@id='txtSearch']").click()
        time.sleep(2)
        self.driver.find_element(By.XPATH, "//input[@id='searchKey']").send_keys("抄表合同")
        time.sleep(2)
        self.driver.find_element(By.XPATH,"//input[@id='btnSearch']").click()
        time.sleep(2)
        self.driver.find_element(By.XPATH, "//li[@id='menu_-2780']").click()
        time.sleep(2)
    def input_pdf(self,pdf_name,pdf_number,pdf_path):
        self.driver.switch_to.default_content()
        WA.WebDriverWait(self.driver, timeout=2).until(EC.frame_to_be_available_and_switch_to_it("iframe_-2780_0_main"))
        time.sleep(2)
        self.driver.find_element(By.XPATH, "//input[@id='KPConditionPanel1_txtCONTRACT_CODE']").clear()
        self.driver.find_element(By.XPATH, "//input[@id='KPConditionPanel1_txtCONTRACT_CODE']").send_keys(f"{pdf_name}")
        time.sleep(2)
        self.driver.find_element(By.XPATH, "//input[@id='KPConditionPanel1_txtBILL_CODE']").clear()
        self.driver.find_element(By.XPATH, "//input[@id='KPConditionPanel1_txtBILL_CODE']").send_keys(f"{pdf_number}")
        loggins.info(f"已在搜索{pdf_name}合同编号,{pdf_number}单号")
        time.sleep(2)
        self.driver.find_element(By.XPATH,"//input[@id='buttonPanel_btnSearch']").click()
        time.sleep(5)
        contract_number = self.driver.find_elements(By.XPATH,"//table[@id='a30de0a0de6f9d798ad073024fab6dd0_table']/tbody/tr")
        if len(contract_number)==0:
            loggins.error(f"根据{pdf_name}合同编号没有查询到结果")
            with open('D:/2/upload.txt','a') as f:
                f.write(f"{pdf_path}合同编号没有查询到结果，文件未上传\n")
            pass
        else:
            for i in range(len(contract_number)):
                # self.driver.switch_to.default_content()
                try:
                    print(i)
                    element = self.driver.find_element(By.XPATH, f"//td[@id='a30de0a0de6f9d798ad073024fab6dd0_tr{i}_tdBILL_CODE']")
                    loggins.info("单号元素存在")
                    element.click()
                except NoSuchElementException:
                    loggins.error("单号元素不存在")

                time.sleep(5)
                WA.WebDriverWait(self.driver, timeout=2).until(EC.frame_to_be_available_and_switch_to_it("DetailIframe"))

                # print("aaaaaaaaaa")
                try:
                    element = self.driver.find_element(By.XPATH, "//div[@id='myAnnexText']")
                    loggins.info("附件元素存在")
                    element_text = element.text
                    loggins.info(f"是否已有附件：{element_text}")
                    time.sleep(3)
                    if element_text == "有":
                        self.driver.switch_to.default_content()
                        WA.WebDriverWait(self.driver, timeout=2).until(EC.frame_to_be_available_and_switch_to_it("iframe_-2780_0_main"))
                        element = self.driver.find_element(By.XPATH, "//div[@onclick='winminClick()']")
                        element.click()
                        loggins.debug(f"因为已有附件，将不再上传该文件")
                        with open('D:/2/upload.txt', 'a') as f:
                            f.write(f"{pdf_path}合同已有附件，将不再上传该文件\n")
                        continue

                except NoSuchElementException:
                    loggins.error("附件元素不存在")
                try:
                    element = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='myAnnexText']")))
                    loggins.info("附件元素可点击")
                    element.click()
                except TimeoutException:
                    loggins.error("附件元素不可点击")
                time.sleep(3)
                # self.driver.find_element(By.XPATH,f"//span[@id='button-1030-btnIconEl']")
                try:
                    self.driver.switch_to.default_content()
                    value = self.driver.find_element(By.XPATH, "//span[@class='ui-dialog-title']").get_attribute("id")
                    id_value = value.split("_")[-1]
                    loggins.info("获取iframe的id值元素存在")
                    loggins.info(f"获取iframe的id值为：{id_value}")
                except NoSuchElementException:
                    loggins.error("获取id值元素不存在")
                WA.WebDriverWait(self.driver, timeout=2).until(EC.frame_to_be_available_and_switch_to_it(f"divDialog_{id_value}_iframe"))
                # self.driver.find_element(By.XPATH, f"//span[@id='button-1030-btnIconEl']").click()
                time.sleep(2)

                """
                在这里点击上传文件，需要填写文件路径
                需要解决填写文件路径问题；需要解决同一个合同编号有两条记录，循环上传问题。
                """
                element = self.driver.find_element(By.XPATH, f"//input[@id='filesUploadInput']")
                js = "arguments[0].removeAttribute('style');"
                self.driver.execute_script(js,element)
                loggins.info("已清除上传格式，恢复源模式")
                time.sleep(2)
                self.driver.find_element(By.XPATH, f"//input[@id='filesUploadInput']").send_keys(pdf_path)
                loggins.info(f"已上传{pdf_name}合同编号路径{pdf_path}")
                with open('D:/2/upload.txt', 'a') as f:
                    f.write(f"{pdf_path}合同已上传\n")
                time.sleep(6)

                alert = self.driver.switch_to.alert
                loggins.info(f"上传文件后弹窗内容：{alert.text}")
                alert.accept()
                self.driver.switch_to.default_content()
                self.driver.find_element(By.XPATH, "//span[@tag='close']").click()
                # self.driver.switch_to.default_content()
                WA.WebDriverWait(self.driver, timeout=2).until(EC.frame_to_be_available_and_switch_to_it("iframe_-2780_0_main"))
                element = self.driver.find_element(By.XPATH, "//div[@onclick='winminClick()']")
                element.click()
                time.sleep(10)

if __name__ == '__main__':
    a = Contract_upload()
    a.search()
    # base_dir = 'C:/Users/yadong_li/Desktop/工作任务/合同/测试'
    # # 获取当前目录下的所有文件
    # files = [os.path.join(base_dir, file).replace("\\","/") for file in os.listdir(base_dir)]
    # # print(files)
    # loggins.info(f"共计{len(files)}个文件")
    # # 遍历文件列表，输出文件名
    # for pdf_path_index,pdf_path in enumerate(files):
    #     pdf_name = pdf_path.split("/")[-1].split(".")[0]
    #     loggins.info(f"正在上传第{pdf_path_index}个文件:{pdf_name}")
    #     a.input_pdf(pdf_name,pdf_path)
    # loggins.info(f"{len(files)}个文件已上传完毕！")

    df = pd.read_excel("D:/2上海未上传合同附件清单20240724.xlsx")
    for index, row in df.iterrows():
        pdf_name = row["合同编号"]
        pdf_number = row["单号"]
    # for pdf_name in df["合同编号"]:
        if os.path.exists(f"D:/2/旧机/{pdf_name}.pdf"):
            a.input_pdf(pdf_name,pdf_number, f"D:/2/旧机/{pdf_name}.pdf")
            loggins.info(f"{pdf_name}.pdf文件存在于D:/2/旧机")

        elif os.path.exists(f"D:/2/全包/{pdf_name}.pdf"):
            a.input_pdf(pdf_name,pdf_number, f"D:/2/全包/{pdf_name}.pdf")
            loggins.info(f"{pdf_name}.pdf文件存在于D:/2/全包")

        elif os.path.exists(f"D:/2/新机/{pdf_name}.pdf"):
            a.input_pdf(pdf_name, pdf_number,f"D:/2/新机/{pdf_name}.pdf")
            loggins.info(f"{pdf_name}.pdf文件存在于D:/2/新机")

        else:
            loggins.info(f"{pdf_name}.pdf文件未找到！")
            with open('D:/2/upload.txt', 'a') as f:
                f.write(f"{pdf_name}.pdf文件夹中未找到！\n")
            continue


